package cn.edu.xmu.oomall.liquidation.model.bo.liquid.calc;

import cn.edu.xmu.oomall.liquidation.microservice.OnSaleService;
import cn.edu.xmu.oomall.liquidation.microservice.OrderService;
import cn.edu.xmu.oomall.liquidation.microservice.ShopService;
import cn.edu.xmu.oomall.liquidation.microservice.vo.Category;
import cn.edu.xmu.oomall.liquidation.microservice.vo.ProductDetailVo;
import cn.edu.xmu.oomall.liquidation.util.GetBeanUtil;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@AllArgsConstructor
@NoArgsConstructor
@Setter
public class CommissionLiquidationItem extends BaseLiquidationItem {
    private OnSaleService onSaleService = GetBeanUtil.getBean(OnSaleService.class);

    private ShopService shopService = GetBeanUtil.getBean(ShopService.class);

    private Logger logger = LoggerFactory.getLogger(CommissionLiquidationItem.class);

    public CommissionLiquidationItem(String dbFieldName) {
        super(dbFieldName);
    }

    @Override
    public Long calcAmount(CalcInfo calcInfo) {
        if (calcInfo instanceof PaymentCalcInfo) {
            return calcPayment((PaymentCalcInfo) calcInfo);
        }
        else if (calcInfo instanceof RefundCalcInfo) {
            return calcRefund((RefundCalcInfo) calcInfo);
        }
        return null;
    }

    private Long calcRefund(RefundCalcInfo refundCalcInfo) {
        //得到商品分类id
        ProductDetailVo productDetailVo = onSaleService.getProductById(refundCalcInfo.getProductId()).getData();
        //得到商品分类佣金率
        Category category = shopService.getCategoryById(productDetailVo.getCategoryId()).getData();

        //计算佣金
        Long priceTotal = refundCalcInfo.getExpenditureItem().getAmount();
        Long commission=category.getCommissionRatio() * priceTotal/1000;

        //修改出账单
        //设置佣金
        refundCalcInfo.getExpenditureItem().setCommission(commission);
        //修改收入
        Long shopRevenue = refundCalcInfo.getExpenditureItem().getShopRevenue();
        refundCalcInfo.getExpenditureItem().setShopRevenue(shopRevenue-commission);
        return commission;
    }

    private Long calcPayment(PaymentCalcInfo paymentCalcInfo) {
        //得到商品分类id
        ProductDetailVo productDetailVo = onSaleService.getProductById(paymentCalcInfo.getProductId()).getData();
        //得到商品分类佣金率
        Category category = shopService.getCategoryById(productDetailVo.getCategoryId()).getData();

        //计算佣金
        Long priceTotal = paymentCalcInfo.getRevenueItem().getAmount();
        Long commission=category.getCommissionRatio() * priceTotal/1000;

        //修改进账单
        //设置佣金
        paymentCalcInfo.getRevenueItem().setCommission(commission);
        //修改商铺收入
        Long shopRevenue = paymentCalcInfo.getRevenueItem().getShopRevenue();
        paymentCalcInfo.getRevenueItem().setShopRevenue(shopRevenue-commission);

        return commission;
    }
}
